//
//  SQTabBarController.swift
//  SwiftWeibo
//
//  Created by suqianghotel on 16/11/14.
//  Copyright © 2016年 suqianghotel. All rights reserved.
//

import UIKit

class SQTabBarController: UITabBarController {
    
    
    fileprivate var timer : Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        setupTabbarViewController()
        
        setupPlusButton()
        
        setupTimer()
        
        setupLaunchView()
        
        self.delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: SQUserShouldLoginNotification), object: nil)
        
        
    }
    
    
    deinit {
        self.timer?.invalidate()
        self.timer = nil
        
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: SQUserShouldLoginNotification), object: nil)
    }
    
    
    
    @objc private func userLogin()
    {
        
        let authVC = SQAuthViewController()
        
        let nav = UINavigationController(rootViewController: authVC)
        
        self.present(nav, animated: true, completion: { () in
        
        })
        
        print(#function)
    }
    
    
    lazy var plusButton: UIButton = {
        var button = UIButton()

        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal);
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal);
        button.addTarget(self, action: #selector(SQTabBarController.clickPlusButton), for: .touchUpInside)
        
        return button
    }()
    
}

/// MARK: 启动图
extension SQTabBarController
{
    fileprivate func setupLaunchView()
    {
        
        if SQHttpManager.shared.logon == false {
            return
        }
        
        // 版本检查
        if Bundle.main.isNewVersion {
            Bundle.main.saveVersion()
            let newFeature = SQLaunchView.launchView()
            view.addSubview(newFeature)

        }else
        {
            let welcomeView = SQWelcomeView.welcomeView()
            view.addSubview(welcomeView)

        }
    }
    
    
}


// MARK: UITabBarControllerDelegate
extension SQTabBarController: UITabBarControllerDelegate
{
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool
    {
    
        if viewController .isMember(of: UIViewController.self) {
            return false
        }
        
        
        
        let nav = viewController as! SQNavigationController
        let idx = tabBarController.viewControllers?.index(of: viewController)
        
        if tabBarController.selectedIndex == 0 && idx == 0 {
          
            
            let home = nav.childViewControllers.first as! SQHomeViewController
    
            
            home.tableview?.setContentOffset(CGPoint(x:0, y:-64), animated: true)
        
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                
                home.loadData()
                
                self.timer?.fire()
            })
            
            
        }
        
        
        return true
    }
}

// MARK: 计时器
extension SQTabBarController
{
    
    fileprivate func setupTimer()
    {
        self.timer = Timer.scheduledTimer(withTimeInterval: 59, repeats: true, block: { timer in
            SQHttpManager.shared.remind_unread_count(success: { unread in
                
                self.tabBar.items?[0].badgeValue = unread!.status > 0 ? "\(unread!.status)" : nil
                    
                print("------------> \(unread!.status)")
                
                UIApplication.shared.applicationIconBadgeNumber =  unread!.status;
                
                
            }, failure: {(msg, code) in
                
            })
        })
    }
    
}


// MARK: 事件
extension SQTabBarController
{
    @objc fileprivate func clickPlusButton(_ button:UIButton)
    {
        
        let menuView = SQComposeMenuView()
        
        menuView.frame = UIScreen.main.bounds
        
        UIApplication.shared.keyWindow?.addSubview(menuView)
        
    }

}


// MARK:tabbar
extension SQTabBarController
{
    func setupPlusButton()
    {
        let with = self.tabBar.bounds.width / CGFloat((viewControllers?.count)!) + 5;
        
        tabBar.addSubview(plusButton)
        
        plusButton.frame = self.tabBar.bounds.insetBy(dx: 2 * with, dy: 0)
        
        
    }
    
    
    func setupTabbarViewController()
    {
        
        
        let filepath = Bundle.main.path(forResource: "main", ofType: "json")
        
        
        
        let jsonData = try? Data(contentsOf: NSURL.fileURL(withPath: filepath!))
        

        let array = try? JSONSerialization.jsonObject(with: jsonData!,
                                                     options:.allowFragments) as! NSArray
        
        
        var arrayM = [UIViewController]()
    
        
        for dict in array!
        {
            arrayM.append(controller(dict: dict as! [String : AnyObject]))
        }
        
        viewControllers = arrayM;
        
    }
    
    
    
    private func controller(dict:[String: AnyObject]) -> UIViewController
    {
        guard
            let className = dict["className"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let visitorInfo = dict["visitorInfo"] as? NSDictionary,
            let clazz = NSClassFromString(Bundle.main.namespace + "." + className) as? SQBaseViewController.Type
        else
        {
            return UIViewController()
        }
        
        let vc = clazz.init()
        vc.vistiorInfo = visitorInfo
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
        
        vc.title = title
        
        let nav = SQNavigationController(rootViewController: vc)
        
        return nav
        
    }
}
